#include <base/Chronometer.h>
#include <extra/rgView.h>

using namespace rg;

LARGE_INTEGER Chronometer::m_freq;

Chronometer::Chronometer (const std::string& label)
	:m_label(label),
	m_lapse(0)
{;}

void Chronometer::init() {
	QueryPerformanceFrequency(&m_freq);
}

void Chronometer::reset() {
	m_lapse = 0;
}

void Chronometer::start() {
	QueryPerformanceCounter(&m_start);
}

void Chronometer::stop()
{
	LARGE_INTEGER end;
	QueryPerformanceCounter(&end);
	m_lapse = 
		(rgReal)((rgReal)(end.QuadPart - m_start.QuadPart) / (rgReal)m_freq.QuadPart) *1000;
}

void Chronometer::lapse()
{
	LARGE_INTEGER end;
	QueryPerformanceCounter(&end);
	m_lapse += 
		(rgReal)((rgReal)(end.QuadPart - m_start.QuadPart) / (rgReal)m_freq.QuadPart) *1000;
}

void Chronometer::output(class view* view, rgUint16 x, rgUint16 y)
{
	view->print(x, y, m_label + rg::ftoa(m_lapse));
}

Chronos& Chronos::Singleton() 
{
	static Chronos singleton;
	return singleton;
}

Chronos::~Chronos()
{
	for(unsigned i=0;i<m_Swatches.size();++i)
	{
		delete m_Swatches[i];
	}
}

Chronometer* Chronos::add(const std::string& label)
{
	Chronometer* ret = new Chronometer(label);
	m_Swatches.push_back (ret);
	return ret;
}

Chronometer* Chronos::get(const std::string& label)
{
	Chronometer* ret = 0;
	unsigned i=0;
	while(i<m_Swatches.size() && m_Swatches[i]->m_label != label)
	{
		i++;
	}
	if (i<m_Swatches.size())
	{
		ret = m_Swatches[i];
	}
	return ret;
}

void Chronos::Output(class view* view, rgUint16 x, rgUint16 y)
{
	for(unsigned i=0;i<m_Swatches.size();++i)
	{
		m_Swatches[i]->output(view, x, y+=10);
	}
}